package v1.com.autoresource.config;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: learning
 * @Package: com.autoresource.config
 * @ClassName: DynamicDataResourceHolder
 * @Description:
 * @Date: 2021/11/1 8:30 下午
 * @Version: 1.0
 */
public class DynamicDataResourceHolder {

    public static final String DATA_SOURCE = "dataSource";

    public static final String DEFAULT_DATA_SOURCE = "defaultDataSource";


    public static final String MASTER_DATA_SOURCE = "masterDataSource";
    public static final String SLAVE_DATA_SOURCE = "slaveDataSource";


    private static ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> {
        Map<String, Object> map = new HashMap<>();
        map.put(DEFAULT_DATA_SOURCE, MASTER_DATA_SOURCE);
        return map;
    });

    public static Object determineCurrentLookupKey() {
        Map<String, Object> objectMap = threadLocal.get();
        Object dataResource = objectMap.get(DATA_SOURCE);
        if (dataResource == null) {
            dataResource = objectMap.get(DEFAULT_DATA_SOURCE);
        }
        return dataResource;
    }


    public static void selectMasterDataResource() {
        threadLocal.get().put(DATA_SOURCE, MASTER_DATA_SOURCE);
    }

    public static void selectSlaveDataResource() {
        threadLocal.get().put(DATA_SOURCE, SLAVE_DATA_SOURCE);
    }
}
